package cn.gcjxsc.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pumbaa
 */
public class HttpClientUtil {
    /**
     * http post 操作
     *
     * @param url    地址
     * @param params 参数
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> params) throws Exception {
        List<NameValuePair> pairs = buildParams(params);
        return doPost(url, new UrlEncodedFormEntity(pairs, "utf-8"));
    }

    /**
     *  http post 操作. 提交xml类的数据
     *
     * @param url  地址
     * @param data 数据
     * @return
     * @throws Exception
     */
    public static String post(String url, String data) throws Exception {
        return doPost(url, new StringEntity(data, "utf-8"));
    }

    /**
     * http get 操作
     * @param url 地址
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        return doGet(url, null);
    }

    /**
     * http get 操作
     * @param url 地址
     * @param params 参数
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> params) throws Exception {
        List<NameValuePair> list = buildParams(params);
        return doGet(url, list);
    }

    private static String doGet(String url, List<NameValuePair> params) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig requestConfig = buildConfig();
        try {
            HttpGet httpGet = new HttpGet();
            httpGet.setConfig(requestConfig);
            if (null != params && params.size() > 0) {
                String queryString = URLEncodedUtils.format(params, "utf-8");
                httpGet.setURI(URI.create(url + "?" + queryString));
            } else {
                httpGet.setURI(URI.create(url));
            }
            CloseableHttpResponse response = client.execute(httpGet);
            try {
                return EntityUtils.toString(response.getEntity(), "utf-8");
            } finally {
                response.close();
            }

        } finally {
            client.close();
        }

    }

    private static String doPost(String url, HttpEntity entity) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(5000)
                .build();
        String result = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            post.setEntity(entity);
            CloseableHttpResponse response = client.execute(post);
            try {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } finally {
                response.close();
            }
        } finally {
            client.close();
        }
        return result;
    }

    private static RequestConfig buildConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(5000)
                .build();
    }


    private static List<NameValuePair> buildParams(Map<String, String> params) {
        List<NameValuePair> list = new ArrayList<>();
        params.forEach((k, v) -> list.add(new BasicNameValuePair(k, v)));
        return list;
    }
}
